package com.yxtp.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.yxtp.entity.User;
import com.yxtp.service.UserService;

/**
 * User实体类
 * 
 * @author Nicky
 * @date 2019年5月28日
 */
@Controller
public class UserController {

	@Autowired
	private UserService userService;

	/*
	 * 登陆模块
	 */
	@RequestMapping("/doLogin")
	public String doLogin(String username, String password, Model model, HttpServletRequest request,
			HttpServletResponse response) {
		User user = userService.selectUserByUsernameAndPwd(username, password);
		if (user == null || "".trim().equals(user)) {
			model.addAttribute("msg1", "用户名或密码错误");
		} else if (user != null && !(user.getPassword().equals(password))) {
			model.addAttribute("msg2", "密码错误");
		} else if (user != null & user.getPassword().equals(password)) {
			request.getSession().setAttribute("user", user);
			model.addAttribute("user", user);
			return "/main.jsp";
		}
		return "/login.jsp";
	}

	/*
	 * 跳转注册
	 */
	@RequestMapping("/toRegister")
	public String toRegister() {
		return "/register.jsp";
	}

	/*
	 * 注册模块
	 */
	@RequestMapping("/doRegister")
	public String doRegister(@RequestParam("username") String username, @RequestParam("password") String password,
			Model model, HttpServletRequest request, HttpServletResponse response) {
		User user = new User();
		username =username.substring(1,username.length());
		user.setUsername(username);
		user.setPassword(password);
		// 查重
		if (userService.selectByUsername(username) != null) {
			// 如数据库返回则存在相同用户名 注册失败
			model.addAttribute("msg1","已存在此用户名" + " "+username);
			return "/register.jsp";
		} else {
			//获取系统时间并转换成String类型存入数据库为注册时间
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			user.setRegisterDate(sdf.format(new Date()));
			userService.addUser(user);
			userService.selectUserByUsernameAndPwd(username, password);
		}
		System.out.println(user);
		return "/main.jsp"; 
	}

	/*
	 * 注销
	 */
	@RequestMapping("/outLogin")
	public String outLogin(HttpSession session) {
		// 通过session.invalidata()方法来注销当前的session
		session.invalidate();
		return "/login.jsp";
	}
	
	/*
	 * 跳转上传页面
	 */
	@RequestMapping("/toUpload")
	public String toUpload(String username,Integer id) {
		return "uploadfile.jsp";
	}

}
